//
//  CommentTextFieldViewController.swift
//  SSComment
//
//  Created by 松松 on 2019/4/18.
//

import UIKit
@_exported import IQKeyboardManagerSwift

open class CommentTextFieldViewController: UIViewController {

    private var bottomSafeHeight : CGFloat{
        if UIApplication.shared.statusBarFrame.height > 20{
            return 34
        }else{
            return 0
        }
    }

    private lazy var textView = { () -> SSPlaceHolderTextView in
        let textV = SSPlaceHolderTextView(frame: CGRect.zero)
        textV.placeHolder = placeholder
        textV.placeHolderColor = placeholderColor
        textV.font = UIFont.systemFont(ofSize: 14)
        textV.textContainer.lineFragmentPadding = 0
        textV.translatesAutoresizingMaskIntoConstraints = false
        textV.returnKeyType = .done
        textV.layoutManager.allowsNonContiguousLayout = false
        textV.enablesReturnKeyAutomatically = true
        textV.scrollsToTop = false
        textV.textContainerInset = UIEdgeInsets.zero

        return textV
    }()

    private lazy var sendButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.layer.backgroundColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1).cgColor
        button.layer.cornerRadius = 5

        return button
    }()

    private var bgBottom : NSLayoutConstraint!
    private var textViewH : NSLayoutConstraint!
    private var placeholder : String = ""
    private var placeholderColor : UIColor = UIColor.lightText
    private var maxLength : Int = 140
    private var textBlock : StringBlock?
    public typealias StringBlock = (String) -> Void


    public init(placeholder: String, placeholderColor: UIColor, maxLength: Int, textHandel: StringBlock?) {
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .overCurrentContext
        self.placeholder = placeholder
        self.placeholderColor = placeholderColor
        self.maxLength = maxLength
        self.textBlock = textHandel

    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override open func viewDidLoad() {
        super.viewDidLoad()
        
        setUI()
        getData()
        setEvent()
    }

    open override func viewWillAppear(_ animated: Bool) {
        IQKeyboardManager.shared.enable = false
    }

    open override func viewWillDisappear(_ animated: Bool) {
        IQKeyboardManager.shared.enable = true
    }

    open override func viewDidAppear(_ animated: Bool) {
        textView.becomeFirstResponder()
    }

    //MARK:设置UI
    func setUI(){
        //防止修改高度的时候跳动
        if #available(iOS 11.0, *) {
            textView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }

        view.backgroundColor = UIColor.clear

        //上方空白区域 点击返回上一页
        let backView = UIView(frame: CGRect.zero)
        backView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(backView)
        let tap = UITapGestureRecognizer(target: self, action: #selector(back))
        backView.addGestureRecognizer(tap)

        //输入框背景view
        let bgView = UIView(frame: CGRect.zero)
        bgView.translatesAutoresizingMaskIntoConstraints = false
        bgView.backgroundColor = #colorLiteral(red: 0.9411764706, green: 0.9215686275, blue: 0.9607843137, alpha: 1)
        view.addSubview(bgView)

        //
        let lineView = UIView(frame: CGRect.zero)
        lineView.translatesAutoresizingMaskIntoConstraints = false
        lineView.backgroundColor = UIColor.lightGray
        bgView.addSubview(lineView)

        let textBgView = UIView(frame: CGRect.zero)
        textBgView.translatesAutoresizingMaskIntoConstraints = false
        textBgView.backgroundColor = UIColor.white
        textBgView.layer.cornerRadius = 10
        textBgView.addSubview(textView)

        bgView.addSubview(textBgView)
        bgView.addSubview(sendButton)

        let bgLeft = NSLayoutConstraint(item: bgView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0)
        let bgRight = NSLayoutConstraint(item: bgView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0)
        bgBottom = NSLayoutConstraint(item: bgView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: -bottomSafeHeight)
        view.addConstraints([bgLeft,bgRight,bgBottom])

        let backLeft = NSLayoutConstraint(item: backView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0)
        let backRight = NSLayoutConstraint(item: backView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0)
        let backTop = NSLayoutConstraint(item: backView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
        let backBottom = NSLayoutConstraint(item: backView, attribute: .bottom, relatedBy: .equal, toItem: bgView, attribute: .top, multiplier: 1, constant: 0)
        view.addConstraints([backLeft,backRight,backTop,backBottom])


        let lineLeft = NSLayoutConstraint(item: lineView, attribute: .left, relatedBy: .equal, toItem: bgView, attribute: .left, multiplier: 1, constant: 0)
        let lineRight = NSLayoutConstraint(item: lineView, attribute: .right, relatedBy: .equal, toItem: bgView, attribute: .right, multiplier: 1, constant: 0)
        let lineTop = NSLayoutConstraint(item: lineView, attribute: .top, relatedBy: .equal, toItem: bgView, attribute: .top, multiplier: 1, constant: 0)
        let lineH = NSLayoutConstraint(item: lineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0.7)
        bgView.addConstraints([lineLeft,lineRight,lineTop])
        lineView.addConstraint(lineH)

        let buttonRight = NSLayoutConstraint(item: sendButton, attribute: .right, relatedBy: .equal, toItem: bgView, attribute: .right, multiplier: 1, constant: -15)
        let buttonBottom = NSLayoutConstraint(item: sendButton, attribute: .bottom, relatedBy: .equal, toItem: bgView, attribute: .bottom, multiplier: 1, constant: -10)
        let buttonH = NSLayoutConstraint(item: sendButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 40)
        let buttonW = NSLayoutConstraint(item: sendButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 90)
        bgView.addConstraints([buttonRight,buttonBottom])
        sendButton.addConstraints([buttonH,buttonW])

        let tvBgLeft = NSLayoutConstraint(item: textBgView, attribute: .left, relatedBy: .equal, toItem: bgView, attribute: .left, multiplier: 1, constant: 15)
        let tvBgRight = NSLayoutConstraint(item: textBgView, attribute: .right, relatedBy: .equal, toItem: sendButton, attribute: .left, multiplier: 1, constant: -12)
        let tvBgTop = NSLayoutConstraint(item: textBgView, attribute: .top, relatedBy: .equal, toItem: bgView, attribute: .top, multiplier: 1, constant: 10)
        let tvBgBottom = NSLayoutConstraint(item: textBgView, attribute: .bottom, relatedBy: .equal, toItem: bgView, attribute: .bottom, multiplier: 1, constant: -10)
        bgView.addConstraints([tvBgLeft,tvBgRight,tvBgTop,tvBgBottom])

        let tvLeft = NSLayoutConstraint(item: textView, attribute: .left, relatedBy: .equal, toItem: textBgView, attribute: .left, multiplier: 1, constant: 5)
        let tvRight = NSLayoutConstraint(item: textView, attribute: .right, relatedBy: .equal, toItem: textBgView, attribute: .right, multiplier: 1, constant: -5)
        let tvTop = NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: textBgView, attribute: .top, multiplier: 1, constant: 5)
        let tvBottom = NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: textBgView, attribute: .bottom, multiplier: 1, constant: -5)
        textBgView.addConstraints([tvTop,tvLeft,tvRight,tvBottom])
        textViewH = NSLayoutConstraint(item: textView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 30)
        textView.addConstraint(textViewH)
    }

    //MARK:获取数据
    func getData(){
        
    }

    //MARK:设置事件
    func setEvent(){
        textView.delegate = self
        sendButton.addTarget(self, action: #selector(sendClick(_:)), for: .touchUpInside)

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

    }
    

    //MARK:返回上一页
    @objc
    private func back(){
        self.textView.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }

    //MARK:发送内容
    @objc
    private func sendClick(_ sender: UIButton){
        if textView.text.isEmpty{
            return
        }
        self.textBlock?(textView.text)
        self.textView.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }

    //MARK:键盘弹出
    @objc
    private func keyboardShow(_ noti: Notification){
        let duration = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let endFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        UIView.animate(withDuration: duration) {
            self.bgBottom.constant = -endFrame.height
        }
    }

    //MARK:键盘消失
    @objc
    private func keyboardHidden(_ noti: Notification){
        let duration = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        UIView.animate(withDuration: duration) {
            self.bgBottom.constant = -self.bottomSafeHeight
        }
    }

    //MARK:键盘的高度发生变化
    @objc
    private func keyboardFrameChange(_ noti: Notification){
        let duration = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let endFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        UIView.animate(withDuration: duration) {
            self.bgBottom.constant = -endFrame.height
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}

extension CommentTextFieldViewController : UITextViewDelegate{

    public func textViewDidChange(_ textView: UITextView) {
        let text = textView.text
        let textH = text?.heightWithWidth(textView.frame.width - 10, font: textView.font!) ?? 0
        let maxH : CGFloat = max(30, textH )
        let minH : CGFloat = min(maxH, 100)
        textView.scrollRangeToVisible(NSRange(location: textView.selectedRange.location, length: 1))
        if minH != textViewH.constant{
            self.textViewH.constant = minH
        }
    }
}

extension String{

    fileprivate func getStringSize(rectSize: CGSize,font: UIFont) -> CGSize {
        let str: NSString = self as NSString
        let rect = str.boundingRect(with: rectSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return CGSize(width: ceil(rect.width), height: ceil(rect.height))
    }

    fileprivate func heightWithWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(
            with: constraintRect,
            options: .usesLineFragmentOrigin,
            attributes: [NSAttributedStringKey.font: font],
            context: nil)
        return boundingBox.height
    }

}

class SSPlaceHolderTextView: UITextView {

    @IBInspectable public var placeHolder: String = ""{
        didSet{
            self.setNeedsDisplay()
        }
    }
    @IBInspectable public var placeHolderColor: UIColor = UIColor.lightText{
        didSet{
            self.setNeedsDisplay()
        }
    }
    @IBInspectable public var maxLength :Int = 140

    public var overstepBlock : ((Bool) -> Void)?

    override var font: UIFont?{
        didSet{
            self.setNeedsDisplay()
        }
    }
    override var text: String!{
        didSet{
            self.setNeedsDisplay()
        }
    }
    override var attributedText: NSAttributedString!{
        didSet{
            self.setNeedsDisplay()
        }
    }


    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        /// default字号
        self.font = UIFont.systemFont(ofSize: 14)
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChanged(noti:)), name: NSNotification.Name.UITextViewTextDidChange, object: self)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc func textDidChanged(noti: NSNotification)  {
        self.setNeedsDisplay()
        self.overstepBlock?(text.count > maxLength)
    }
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        if self.hasText {
            return
        }

        let newRect = CGRect(x: contentInset.left, y: contentInset.top, width: rect.width - contentInset.left - contentInset.right, height: rect.height - contentInset.top - contentInset.bottom)

        /// 将placeHolder画在textView上
        let attrStr = NSMutableAttributedString(string: self.placeHolder)
        attrStr.addAttributes([NSAttributedString.Key.font: self.font ?? UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor: self.placeHolderColor], range: NSRange(location: 0, length: attrStr.length))
        attrStr.draw(in: newRect)

    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.setNeedsDisplay()
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextViewTextDidChange, object: self)
    }

}



